<template>
    <Modal :mask-closable="false" v-model="deviceVisible" title="新建工单">
        <Form ref="deviceForm" :model="formTop" label-position="top" :rules="validateDevice">
            <Row :gutter="16">
                <Col :span="24">
                <FormItem label="设备编号：" prop="deviceMId">
                    <Select v-model="formTop.deviceMId" filterable clearable :remote-method="handleRemote"
                        :loading="searchLoading" @on-select="handleChangeWl">
                        <Option v-for="item in numberList" :value="item.deviceMId" :key="item.deviceMId">{{ item.deviceMId
                        }}</Option>
                    </Select>
                </FormItem>
                </Col>
                <Col :span="24">
                <FormItem :label="`${$t('ledger.EquipmentNo')}:`">
                    <Input v-model="formTop.deviceNo" clearable disabled />
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="24">
                <FormItem label="生产料号：" prop="productNo">
                    <Input v-model="formTop.productNo" clearable />
                </FormItem>
                </Col>
                <Col :span="24">
                <FormItem label="故障时间：" prop="faultTime">
                    <DatePicker :options="optionsdate" v-model="formTop.faultTime" type="datetime"
                        format="yyyy-MM-dd HH:mm:ss" placeholder="">
                    </DatePicker>
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="24">
                <FormItem label="报修日期：">
                    <span>{{ formTop.repairDate }}</span>
                </FormItem>
                </Col>
                <Col :span="24">
                <FormItem label="报修人：">
                    <span>{{ formTop.username }}</span>
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="24">
                <FormItem label="报修电话：" prop="faultPhone">
                    <Input maxlength="11" v-model="formTop.faultPhone" clearable />
                </FormItem>
                </Col>
                <Col :span="24">
                <FormItem label="维修迫切程度：" prop="urgentLevel">
                    <Select v-model="formTop.urgentLevel">
                        <Option v-for="item in levels" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="24">
                <FormItem label="是否影响生产：" prop="effected">
                    <Select v-model="formTop.effected">
                        <Option v-for="item in effects" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                </Col>
                <Col :span="24">
                <FormItem label="故障分类：" prop="classify">
                    <Cascader :data="treeData" clearable class="Input-wrapper" v-model="formTop.classify"></Cascader>
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="24">
                <FormItem label="故障现象：" prop="faultNote">
                    <Input type="textarea" :rows="4" v-model="formTop.faultNote" clearable />
                </FormItem>
                </Col>
            </Row>
        </Form>
        <div slot="footer">
            <Button type="default" @click="handleCancel">{{ $t('common.Cancle') }}</Button>
            <Button type="primary" :loading="loadingVisible" @click="handleOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
    </Modal>
</template>

<script>
export default {
    name: "addModal",
    data() {
        const checkPhone = (rule, value, callback) => {
            let regPone = null
            let mobile = /^(1[3456789]\d{9})$/
            let tel = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/
            if (value !== null && value.charAt(0) === '0') {
                regPone = tel
            } else if (value !== null && value.charAt(0) !== '0') {
                regPone = mobile
            }
            if (regPone === null) {
                return callback(new Error('请输入电话'))
            } else if (!regPone.test(value)) {
                return callback(new Error('请输入正确的电话格式'))
            } else {
                callback()
            }
        }
        return {
            optionsdate: {
                disabledDate(date) {
                    return date && date.getTime() > Date.now();
                }
            },
            deviceVisible: false,
            loadingVisible: false,
            searchLoading: false,
            formTop: {
                username: window.localStorage.getItem('ziyunFactoryPortalName'),
                repairDate: this.$moment(new Date()).format('YYYY-MM-DD'),
                classify: [],
                deviceMId: '',
                faultTime: '',
                faultPhone: '',
                urgentLevel: '',
                effected: '',
                faultNote: '',
                productNo: '',
            },
            validateDevice: {
                deviceMId: [
                    { required: true, message: '请选择设备编号', trigger: 'change' }
                ],
                productNo: [
                    { required: true, message: '请输入生产料号', trigger: 'blur' }
                ],
                faultTime: [
                    { required: true, type: 'date', message: '请选择故障时间', trigger: 'change' }
                ],
                faultPhone: [
                    { required: true, message: '请输入正确的电话号码', validator: checkPhone, trigger: ["blur"] }
                ],
                urgentLevel: [
                    { required: true, message: '请选择维修迫切程度', trigger: 'change' }
                ],
                effected: [
                    { required: true, message: '请选择影响程度', trigger: 'change' }
                ],
                classify: [
                    { required: true, type: 'array', message: '请选择故障性质', trigger: 'change' }
                ],
                faultNote: [
                    { required: true, message: '请输入故障现象', trigger: 'change' }
                ],
            },
            numberList: [],
            treeData: [],
            levels: [{ label: '特急', value: '1' }, { label: '紧急', value: '2' }, { label: '一般', value: '3' }],
            effects: [{ label: '影响生产', value: '1' }, { label: '不影响生产', value: '2' }],
        }
    },

    mounted() {
        this.getClassfiyList()
        let itemList = window.localStorage.getItem('ziyunFactoryPortalName')
        console.log(itemList)
    },
    watch: {
        // formTop: {
        //     handler(val) {
        //         console.log(val)
        //         // this.$nextTick(() => {
        //         //     this.getStockNum(this.formTop.maCode, this.workorderNo)
        //         // })
        //     },
        //     deep: true
        // }
    },
    methods: {
        checkPhone(value) {
            let regPone = null
            let mobile = /^(1[3456789]\d{9})$/
            let tel = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/
            if (value !== null && value.charAt(0) === '0') {
                regPone = tel
            } else if (value !== null && value.charAt(0) !== '0') {
                regPone = mobile
            }
            if (regPone === null) {
                return false
            } else if (!regPone.test(value)) {
                return false
            } else {
                return true
            }
        },
        getClassfiyList() {
            this.axios({
                method: 'get',
                url: '/workorder/workorderDealType/selectList',
                params: {}
            }).then(res => {
                if (res.code === 200) {
                    this.treeData = res.data
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
                }
            })
        },
        show() {
            this.$refs.deviceForm.resetFields();
            this.deviceVisible = true
        },
        handleRemote(query) {
            if (query !== '') {
                this.searchLoading = true;
                this.axios({
                    method: 'get',
                    url: '/workorder/workorder/deviceList',
                    params: {
                        deviceMId: query,
                    }
                }).then(res => {

                    if (res.code === 200) {
                        this.numberList = res.data
                    } else {
                        this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
                    }
                }).finally(() => {
                    this.searchLoading = false
                })
            } else {
                this.numberList = [];
            }
        },
        handleChangeWl(val) {
            console.log(val)
            console.log(this.numberList)
            let arr = this.numberList.length ? this.numberList.filter(item => item.deviceMId === val.value) : []
            console.log(arr)
            this.formTop.deviceNo = arr[0].deviceNo
        },
        handleCancel() {
            this.deviceVisible = false
            this.loadingVisible = false
        },
        handleOk() {
            let { deviceMId, effected, faultNote, faultPhone, faultTime, productNo, urgentLevel, classify } = this.formTop
            const flag = this.checkPhone(faultPhone)
            if (!flag) {
                return
            }
            let params = {
                deviceMId,
                productNo,
                faultTime: this.$moment(faultTime).format('YYYY-MM-DD HH:mm:ss'),
                faultPhone,
                urgentLevel,
                effected,
                faultNote,
                firstclass: classify[0],
                secondclass: classify[1],
                workorderAttachmentList: []
            }
            this.$refs.deviceForm.validate((valid) => {
                if (valid) {
                    this.loadingVisible = true
                    this.axios({
                        method: 'post',
                        url: '/workorder/workorder/add',
                        data: params
                    }).then(res => {

                        if (res.code === 200) {
                            this.deviceVisible = false
                            this.loadingVisible = false
                            this.$Message.success('新增成功！')
                            this.$refs.deviceForm.resetFields();
                            this.$emit('refresh')
                        } else {
                            this.deviceVisible = false
                            this.loadingVisible = false
                            this.$Message.error(res.msg)
                        }
                    })
                }
            }).finally(() => {

            })
        },
    }
}
</script>

<style scoped></style>
